//
//  weibonetwork.swift
//  weibo
//
//  Created by jason on 2017/3/4.
//  Copyright © 2017年 jason. All rights reserved.
//



//https://api.weibo.com/oauth2/authorize?client_id=3830409095&redirect_uri=http://baidu.com
//https://www.baidu.com/?code=cbe3c35e67bfb7bc1a1bdfeca3cece4b



import UIKit
import AFNetworking
enum wbhttpmethod{
    case GET
    case POST
}

class weibonetwork: AFHTTPSessionManager {
    static let shared = weibonetwork()
    
    var accesstoken:String? = "2.00xYDXiG4Gn1GC6a9597fdf70K4FIL"
    var uid:String? = "6154834299"
    
    func tokenrequest(method:wbhttpmethod = .GET, URLString: String,parameters:[String:AnyObject]?,completion:@escaping (_ json:AnyObject?,_ issuccess:Bool)->()){
        var parameters = parameters
        guard let token = accesstoken else {
            //FIXME:发送通知,提示用户登录
            print("没有token")
            completion(nil,false)
            return
        }
        
        if parameters == nil{
            parameters = [String:AnyObject]()
        }
        parameters!["access_token"] = token as AnyObject?
        
        request(URLString: URLString, parameters: parameters!, completion: completion)
        
    }
    func request(method:wbhttpmethod = .GET, URLString: String,parameters:[String:AnyObject]?,completion:@escaping (_ json:AnyObject?,_ issuccess:Bool)->()){
        let success = {
            (task:URLSessionDataTask,json:Any?)->() in
            completion(json as AnyObject?,true)
        }
        let faliure = {
            (task:URLSessionDataTask?,error:Error)->() in
            //针对403 处理用户过期
            //FIXME:发送通知,提示用户登录2
            if (task?.response as? HTTPURLResponse)?.statusCode == 403{
                print("token过期了")
            }
           
            completion(nil,false)
        }
        
        
        if method == .GET{
            get(URLString, parameters: parameters, progress: nil, success: success, failure: faliure)
        }else{
            post(URLString, parameters: parameters, progress: nil, success: success, failure: faliure)
        }
        
    }
    }
